/**
 * 
 */
package org.jenkon.io.iterator;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Iterator;
import java.util.NoSuchElementException;

import org.jenkon.Closable;
import org.jenkon.io.utils.IOUtils;

/**
 * <p>
 * {@link Iterator} to loop over all lines of a {@link File}.
 * </p>
 * 
 * @author Jens Konopka
 * 
 */
public class LineFileIterator implements Iterator<String>, Closable {

	/**
	 * 
	 */
	private static final long serialVersionUID = 3872542526805658082L;

	private final BufferedReader reader;
	private String currentLine;

	/**
	 * @param reader {@link BufferedReader}
	 */
	public LineFileIterator(final BufferedReader reader) {
		this.reader = reader;
	}

	/**
	 * @param reader {@link FileReader}
	 */
	public LineFileIterator(final FileReader reader) {
		this(new BufferedReader(reader));
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.util.Iterator#hasNext()
	 */
	public boolean hasNext() {
		try {
			currentLine = reader.readLine();
			if (currentLine == null) {
				close();
			}
		} catch (final IOException e) {
			close();
			throw new IllegalStateException(e);
		}
		return currentLine != null;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.util.Iterator#next()
	 */
	public String next() {
		if (currentLine == null) {
			close();
			throw new NoSuchElementException("No more lines at the file");
		}
		return currentLine;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see java.util.Iterator#remove()
	 */
	public void remove() {
		throw new UnsupportedOperationException("Remove unsupported on " + this);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.jenkon.Closable#close()
	 */
	public void close() {
		IOUtils.close(reader);
	}

}
